package org.transfer.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.transfer.model.ImportLog;
import org.transfer.utils.ConfigUtil;
import org.transfer.utils.DecompUtils;
import org.transfer.utils.LogUtils;

@Component
public class DecompressionService {

	@Autowired
	private ImportLogService importLogService;

	private String logPath = "";

	/**
	 * 解压方法
	 * 
	 * @throws IOException
	 */
	public void decompression() throws IOException {
		System.out.println("===================解压开始===================");
		// 源压缩文件地址
		String decompressionPath = ConfigUtil.getConfigure().getProperty("decompressionPath");
		// 解压后存放的目录地址
		String decompressionOutPath = ConfigUtil.getConfigure().getProperty("decompressionOutPath");
		String logsFile = ConfigUtil.getConfigure().getProperty("logsFile");
		File logFile = new File(logsFile);
		if (!logFile.exists()) {
			logFile.mkdirs();
		}
		logPath = logsFile + "decomp.log";
		// 开始解压
		File file = new File(decompressionPath);
		File[] files = file.listFiles();
		List<File> outlist = new ArrayList<File>();
		scanningFile(outlist, decompressionOutPath);
		for (File f : files) {
			if (f.isFile()) {
				// 需要解密状态
				boolean flag = true;
				// 判断如果输出文件夹有该文件则无需解密
				for (File outFile : outlist) {
					if (f.getName().indexOf(outFile.getName()) != -1) {
						flag = false;
						break;
					}
				}
				if (!flag) {
					LogUtils.logs(logPath, "【" + f.getName() + "】无需解压");
					continue;
				}
				ImportLog entity = importLogService
						.get(new ImportLog(f.getName().substring(0, f.getName().indexOf("."))));
				try {
					DecompUtils.decompression7z(f.getPath(), decompressionOutPath);
					System.out.println("---------【" + f.getName() + "】解压完毕！----------");
					LogUtils.logs(logPath, "【" + f.getName() + "】解压成功");
					if (entity != null) {
						entity.setDecompState("1");
						entity.setDecompMsg("解压成功");
						importLogService.save(entity);
					}
				} catch (Exception e) {
					LogUtils.logs(logPath, "【" + f.getName() + "】解压失败");
					if (entity != null) {
						entity.setDecompState("0");
						entity.setDecompMsg("解压失败，系统内部错误！");
						importLogService.save(entity);
					}
				}
			} else {
				LogUtils.logs(logPath, "【" + f.getName() + "】解压失败");
			}
		}
		System.out.println("===================解压结束===================");
	}

	public List<File> scanningFile(List<File> list, String filePath) {
		File document = new File(filePath);
		if (!document.exists()) {
			document.mkdirs();
		}
		if (!document.isFile()) {
			File[] files = document.listFiles();
			for (File file : files) {
				scanningFile(list, file.getPath());
			}
		} else {
			list.add(document);
		}
		return list;
	}

}
